﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;

using SpectationClient.SpectralTools;
using SpectationClient.DataBaseDescription;
using SpectationClient.GUI;
using SpectationClient.Stuff;

namespace SpectationClient.DGVExtensions {
    

    public class DataGridViewSpectrumColumn : DataGridViewExtensionBaseColumn {

        public Boolean ToolStripLabel_ShowSpectra { get; set; }

        public override TableInfo TableInfo {
            get { return (this.ColumnInfo == null) ? null: this.ColumnInfo.Table; }
        }

        
        protected new ColumnInfoSpectralFile  columnInfo;
        public new ColumnInfoSpectralFile ColumnInfo {
            get {

                return this.columnInfo;
            }
        }

        public DataGridViewSpectrumColumn() {
            this.init();
        }
        public DataGridViewSpectrumColumn(ColumnInfoSpectralFile columnInfoSpectralFile) {
            this.columnInfo = columnInfoSpectralFile;

            this.init();  
        }

        private void init() {
            this.CellTemplate = new DataGridViewSpectrumCell();
            this.ReadOnly = true;
            
        }

        /// <summary>
        /// Creates a new context menue strip for this DataGridViewColumn and 
        /// adds some tool strip labels.
        /// </summary>
        /// <param name="addShowLabel">Label to open a spectral viewer an show selected spectra</param>
        /// <param name="addSaveLabel">Label to save selected spectra</param>
        /// <param name="addRemoveLabel">Label to remove selected spectra</param>
        public ContextMenuStrip setToolStripLabels(bool addShowLabel, bool addSaveLabel, bool addRemoveLabel) {
            this.ContextMenuStrip = new ContextMenuStrip();
            if(addShowLabel) {
                ToolStripMenuItem label = new ToolStripMenuItem("Zeige markierte Spektren");
                label.Click +=new EventHandler(label_showClick);
                this.ContextMenuStrip.Items.Add(label);
            }

            if(addSaveLabel) {
                ToolStripMenuItem label = new ToolStripMenuItem("Speichere Spektren als...");
                
                ToolStripMenuItem labelASD = new ToolStripMenuItem("ASD FieldSpec Format");
                ToolStripMenuItem labelESL = new ToolStripMenuItem("ENVI Spectral Library");
                labelASD.Click +=new EventHandler(label_saveASDClick);
                labelESL.Click +=new EventHandler(label_saveESLClick);
                
                label.DropDownItems.Add(labelASD);
                label.DropDownItems.Add(labelESL);
                this.ContextMenuStrip.Items.Add(label);
            }

            if(addRemoveLabel) {
                ToolStripMenuItem item = new ToolStripMenuItem("Entferne markierte Spektren");
                item.Click +=new EventHandler(label_removeClick);
                this.ContextMenuStrip.Items.Add(item);
            
            }
            return ContextMenuStrip;
        }

        void label_removeClick(object sender, EventArgs e) {
            foreach(DataGridViewSpectrumCell cell in getSelectedCells()) {
                cell.Value = null;
            }
        }

        void label_saveESLClick(object sender, EventArgs e) {
        
            
            SaveFileDialog SFD = new SaveFileDialog();
            SFD.AddExtension = true;
            SFD.DefaultExt = ".sli";
            SFD.Filter = "ENVI Spectral Library (*.sli)|*.sli";
            SFD.FileName = "spektren";

            if(SFD.ShowDialog() == DialogResult.OK) {
                FileInfo fileInfo = new FileInfo(SFD.FileName);
                
                String extension = fileInfo.Extension;
                ESL_Writer ESL_Writer = new ESL_Writer();
                
                List<Spectrum> spectra = (from DataGridViewSpectrumCell cell in getSelectedCells(true)
                                                 where cell.Value != null && cell.getSpectrum() != null
                                                 select cell.getSpectrum()).ToList();
                if(spectra != null && spectra.Count > 0) {
                    ESL_Writer.createESLFiles(fileInfo, spectra);
                }

                this.DataGridView.Cursor = Cursors.Default;
            }
        }

        void label_saveASDClick(object sender, EventArgs e) {
            List<DataGridViewCell> cells = getSelectedCells(true);
            SaveFilesDialog SID = new SaveFilesDialog(this.DataGridView);
            if(SID.ShowDialog() == DialogResult.OK) {
                this.DataGridView.Cursor = Cursors.WaitCursor;


                String folder = SID.Folder;
                String extension = "."+SID.FileExtension;
                bool useRowNumbers = SID.UseRowNumbers;
                ASD_Writer ASD_Writer = new SpectralTools.ASD_Writer();

                String[] cols = SID.FileNameColumns;
                foreach(DataGridViewSpectrumCell c in cells) {
                    String filename;
                    if(useRowNumbers) {
                        filename = String.Format("{0}{1}", this.Name, c.RowIndex+1);

                    } else {
                        String[] columnValues = (from String column in cols
                                                 let otherCell = this.DataGridView[column, c.RowIndex]
                                                 where otherCell.Value != null
                                                 select otherCell.Value.ToString()).ToArray();
                        filename = String.Format("{0}_{1}",
                                        this.Name,
                                        TextHelper.combine(columnValues, "_"));
                    }
                    filename = DataHelper.createNewFilePath(new FileInfo(SID.Folder + "\\"+ filename + extension)).FullName;
                    Spectrum spectrum = c.getSpectrum();
                    ASD_Writer.createASDFile(filename, spectrum);

                }
                this.DataGridView.Cursor = Cursors.Default;

            }
        }


        void label_showClick(object sender, EventArgs e) {
            GUI.ViewSpectraForm View = new ViewSpectraForm();
            View.linkToSpectrumColumn(this);
            View.Show();
        }


    }



}
